package com.java.blocking_queue;

import com.java.producer_consumer.Container;

import java.util.concurrent.BlockingQueue;

/**
 * 消费者：从阻塞队列中取数据
 */
public class Consumer extends Thread {
    // 生产者和消费者的阻塞队列必须是同一条
    private BlockingQueue<String> blockingQueue;

    public Consumer(BlockingQueue blockingQueue) {
        this.blockingQueue = blockingQueue;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (Container.key) {
                try {
                    String data = blockingQueue.take();
                    // 此处打印可能会存在多线程安全问题，因为锁是加载take内部的。打印的目的是为了看效果，实际是没问题的
                    System.out.println("消费者消费，数据数量为" + blockingQueue.size());
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
